package commands;

import user.User;
import messages.ChatFailedMessage;
import messages.ChatMessage;
import messages.Message;
import core.UserManager;
import event.ChatEventArgs;
import event.ChatFailedEventArgs;


/**
 * The Chat command.
 * 
 * This command will handle chat messages.
 */
public class ChatCommand extends Command {

	
	public ChatCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		UserManager userManager = controller.getUserManager();
		ChatMessage message = (ChatMessage) this.message;
		message.setOriginLogin(this.user.getLogin());
		
		synchronized(userManager) {
			
			if (userManager.isLoggedIn(message.getDestinyLogin())) {	
				this.controller.fireChatEvent(new ChatEventArgs(message));
			} else {
				this.controller.fireChatFailedEvent(new ChatFailedEventArgs(
						new ChatFailedMessage(message, ChatFailedMessage.ErrorCode.UnknownUser)));
			}
		}
	}
}
